package com.christina.engine.processing;

import com.christina.engine.processing.model.ProcessingContext;
import com.christina.engine.processing.model.ProcessingEvent;
import com.christina.engine.processing.model.ProcessingEventType;
import com.christina.engine.processing.model.ProcessingResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 抽象请求处理器
 * 提供责任链模式的通用实现和模板方法
 */
public abstract class AbstractRequestProcessor implements RequestProcessor {
    
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    
    private RequestProcessor next;
    private final String name;
    private final int order;
    private boolean enabled = true;
    
    protected AbstractRequestProcessor(String name, int order) {
        this.name = name;
        this.order = order;
    }
    
    @Override
    public final ProcessingResult process(ProcessingContext context) {
        if (!isEnabled()) {
            logger.debug("Processor {} is disabled, skipping", getName());
            return ProcessingResult.success(getName());
        }
        
        if (!supports(context)) {
            logger.debug("Processor {} does not support current context, skipping", getName());
            return ProcessingResult.success(getName());
        }
        
        logger.debug("Starting processing with {}", getName());
        long startTime = System.currentTimeMillis();
        
        try {
            // 添加处理开始事件
            context.addEvent(ProcessingEvent.builder()
                    .type(ProcessingEventType.REQUEST_RECEIVED)
                    .message("Processing started by " + getName())
                    .source(this)
                    .build());
            
            // 执行前置处理
            preProcess(context);
            
            // 执行核心处理逻辑
            ProcessingResult result = doProcess(context);
            
            // 执行后置处理
            postProcess(context, result);
            
            long executionTime = System.currentTimeMillis() - startTime;
            
            // 更新执行时间
            ProcessingResult finalResult = ProcessingResult.builder()
                    .success(result.isSuccess())
                    .shouldContinue(result.isShouldContinue())
                    .errorMessage(result.getErrorMessage())
                    .exception(result.getException())
                    .resultData(result.getResultData())
                    .metadata(result.getMetadata())
                    .processorName(getName())
                    .executionTimeMs(executionTime)
                    .build();
            
            // 添加处理完成事件
            context.addEvent(ProcessingEvent.builder()
                    .type(result.isSuccess() ? ProcessingEventType.SERVICE_EXECUTED : ProcessingEventType.ERROR_OCCURRED)
                    .message("Processing " + (result.isSuccess() ? "completed" : "failed") + " by " + getName())
                    .source(this)
                    .eventData("executionTimeMs", executionTime)
                    .eventData("success", result.isSuccess())
                    .build());
            
            logger.debug("Completed processing with {} in {}ms, success: {}, continue: {}", 
                    getName(), executionTime, result.isSuccess(), result.isShouldContinue());
            
            return finalResult;
            
        } catch (Exception e) {
            long executionTime = System.currentTimeMillis() - startTime;
            logger.error("Error in processor {}: {}", getName(), e.getMessage(), e);
            
            // 添加错误事件
            context.addEvent(ProcessingEvent.errorOccurred(
                    "Error in processor " + getName() + ": " + e.getMessage(), e));
            
            // 执行错误处理
            ProcessingResult errorResult = handleError(context, e);
            
            return ProcessingResult.builder()
                    .success(errorResult.isSuccess())
                    .shouldContinue(errorResult.isShouldContinue())
                    .errorMessage(errorResult.getErrorMessage() != null ? 
                            errorResult.getErrorMessage() : e.getMessage())
                    .exception(errorResult.getException() != null ? errorResult.getException() : e)
                    .resultData(errorResult.getResultData())
                    .metadata(errorResult.getMetadata())
                    .processorName(getName())
                    .executionTimeMs(executionTime)
                    .build();
        }
    }
    
    /**
     * 核心处理逻辑，由子类实现
     * 
     * @param context 处理上下文
     * @return 处理结果
     */
    protected abstract ProcessingResult doProcess(ProcessingContext context);
    
    /**
     * 前置处理钩子方法
     * 子类可以重写此方法来执行预处理逻辑
     * 
     * @param context 处理上下文
     */
    protected void preProcess(ProcessingContext context) {
        // 默认实现为空，子类可以重写
    }
    
    /**
     * 后置处理钩子方法
     * 子类可以重写此方法来执行后处理逻辑
     * 
     * @param context 处理上下文
     * @param result 处理结果
     */
    protected void postProcess(ProcessingContext context, ProcessingResult result) {
        // 默认实现为空，子类可以重写
    }
    
    /**
     * 错误处理钩子方法
     * 子类可以重写此方法来自定义错误处理逻辑
     * 
     * @param context 处理上下文
     * @param exception 发生的异常
     * @return 错误处理结果
     */
    protected ProcessingResult handleError(ProcessingContext context, Exception exception) {
        // 默认错误处理：记录错误并停止处理
        return ProcessingResult.failure(
                "Error in processor " + getName() + ": " + exception.getMessage(),
                exception,
                getName()
        );
    }
    
    @Override
    public void setNext(RequestProcessor next) {
        this.next = next;
    }
    
    @Override
    public RequestProcessor getNext() {
        return next;
    }
    
    @Override
    public String getName() {
        return name;
    }
    
    @Override
    public int getOrder() {
        return order;
    }
    
    @Override
    public boolean isEnabled() {
        return enabled;
    }
    
    /**
     * 设置处理器启用状态
     * 
     * @param enabled 是否启用
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
    
    @Override
    public boolean supports(ProcessingContext context) {
        // 默认实现：支持所有上下文
        // 子类可以重写此方法来实现特定的支持逻辑
        return true;
    }
    
    /**
     * 执行责任链中的下一个处理器
     * 
     * @param context 处理上下文
     * @return 下一个处理器的处理结果，如果没有下一个处理器则返回成功结果
     */
    protected ProcessingResult processNext(ProcessingContext context) {
        if (next != null) {
            return next.process(context);
        } else {
            logger.debug("No next processor found, chain completed");
            return ProcessingResult.success("ChainCompleted");
        }
    }
    
    /**
     * 检查是否有下一个处理器
     * 
     * @return 如果有下一个处理器返回true，否则返回false
     */
    protected boolean hasNext() {
        return next != null;
    }
    
    @Override
    public String toString() {
        return "AbstractRequestProcessor{" +
                "name='" + name + '\'' +
                ", order=" + order +
                ", enabled=" + enabled +
                ", hasNext=" + hasNext() +
                '}';
    }
}